package io.plus.server.command.command_handler;

import io.plus.common.io;
import io.plus.common.packet.message.ChatMessage;
import io.plus.common.packet.message.ChatType;
import io.plus.common.packet.metadata.Command;
import io.plus.common.protocol.Packet;
import io.plus.engine.pulse.AsynchronousSocketChannelContext;
import io.plus.server.Status;
import io.plus.server.UserConfiguration;
import io.plus.server.command.CommandHandler;
import io.plus.server.utils.ChatKit;
import io.plus.server.utils.JsonKit;
import tool.plus.ShouldNeverHappenException;

/**
 * 聊天请求cmd消息命令处理器
 */
public class ChatCommandHandler implements CommandHandler {

    @Override
    public Command command() {
        return Command.chat_request;
    }

    @Override
    public Packet handler(UserConfiguration userConfiguration, AsynchronousSocketChannelContext asynchronousSocketChannelContext, Packet packet) throws Exception {
        if (packet.getBody() == null) {
            throw new Exception("body is null");
        }

        ChatMessage chatMessage = JsonKit.toBean(packet.getBody(), ChatMessage.class);
        packet.setBody(chatMessage.toByte());

        Packet chatPacket = new Packet(Command.chat_request, Status.ok, chatMessage.toByte());
        //设置同步序列号;
        chatPacket.setSynchronismSerialNumber(packet.getSynchronismSerialNumber());
        //私聊
        if (ChatType.private_chat.getNumber() == chatMessage.getChatType()) {
            String to = chatMessage.getTo();
            if (ChatKit.isOnline(to, userConfiguration)) {
                io.sendToUser(to, chatPacket);
                //发送成功响应包
                return ChatKit.sendSuccessRespPacket(asynchronousSocketChannelContext);
            } else {
                //用户不在线响应包
                return ChatKit.offlineRespPacket(asynchronousSocketChannelContext);
            }
            //群聊
        } else if (ChatType.group_chat.getNumber() == chatMessage.getChatType()) {
            String groupId = chatMessage.getGroupId();
            io.sendToGroup(groupId, chatPacket);
            //发送成功响应包
            return ChatKit.sendSuccessRespPacket(asynchronousSocketChannelContext);
        } else {
            throw new ShouldNeverHappenException();
        }

    }
}
